package channelService

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/ChanSyncObj"
	"go-fox-edge-channel-tcp-client/channelEntity"
	"io"
	"net"
	"time"
)

func scheduler() {
	for {
		channelName2Entity := service.getChannelNames()
		for _, value := range channelName2Entity {
			entity := value.(*channelEntity.TcpClientEntity)

			// 检查：南向通道是否建立，如果没有建立，那么重新发起连接
			conn := channelManager.getContextByRemoteAddr(entity.SocketAddress)
			if conn == nil {
				conn, err := net.Dial("tcp", entity.SocketAddress)
				if err != nil {
					commLogger.Error("连接失败: " + entity.ChannelName + ", socketAddress=" + entity.SocketAddress + " 原因：" + err.Error())
					continue
				}

				channelManager.setServiceKey(conn, entity.ChannelName)
				commLogger.Info("建立连接: " + entity.ChannelName + ", socketAddress=" + entity.SocketAddress)

				// 启动一个读取线程
				go reader(conn, entity.ChannelName, entity.RecvBuffSize)
			}
		}

		time.Sleep(5 * time.Second)
	}
}

func reader(conn net.Conn, channelName string, buffSize int) {
	buf := make([]byte, buffSize)
	for {
		cnt, err := conn.Read(buf)
		if err == io.EOF {
			break
		} else if err == nil && cnt > 0 {
			ChanSyncObj.Notify(channelName, buf[:cnt])
		}
	}

	sktAddr := conn.RemoteAddr().String()
	commLogger.Info("断开连接: " + channelName + ", socketAddress=" + sktAddr)

	// 关闭连接
	conn.Close()

	// 删除信息
	channelManager.removeByRemoteAddr(sktAddr)
}
